package com.example.developerlab;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class AudioManagerTest extends Activity {
    private static final String TAG = AudioManagerTest.class.getSimpleName();

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
                if (intent.hasExtra("state")) {
                    if (intent.getIntExtra("state", 0) == 1) {
                        Toast.makeText(AudioManagerTest.this, "插入耳机", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(AudioManagerTest.this, "拔出耳机", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 监听耳机插入
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        intentFilter.addAction("android.media.VOLUME_CHANGED_ACTION");
        registerReceiver(mReceiver, intentFilter);

        // 定时检查蓝牙连接
        new Thread(() -> {
            while (true) {
                if (isBluetoothHeadsetOn()) {
                    runOnUiThread(() -> Toast.makeText(AudioManagerTest.this, "插入蓝牙耳机", Toast.LENGTH_LONG).show());
                }
                try {
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private boolean isBluetoothHeadsetOn() {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager == null) {
            return false;
        }
        Log.d(TAG, "isBluetoothScoOn=" + audioManager.isBluetoothScoOn() + " " +
                "isBluetoothA2dpOn=" + audioManager.isBluetoothA2dpOn());
        return audioManager.isBluetoothScoOn() || audioManager.isBluetoothA2dpOn();
    }

    private boolean isWiredHeadsetOn() {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager == null) {
            return false;
        }
        Log.d(TAG, "isWiredHeadsetOn=" + audioManager.isWiredHeadsetOn());
        return audioManager.isWiredHeadsetOn();
    }

    private boolean isHeadsetOn() {
        return isWiredHeadsetOn() || isBluetoothHeadsetOn();
    }
}